<?php

use think\migration\Migrator;
use app\model\CouponBrand;

class AlterCouponBrandAddBackupsImg extends Migrator
{
    public function up()
    {
        $sql = <<<SQL
            ALTER TABLE `coupon_brand` ADD COLUMN `old_image` varchar(800) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '备份图片';
SQL;
        $this->execute($sql);
        CouponBrand::query()
            ->field('id, image_url, icon, old_image')
            ->chunk(50, function ($list) {
                if (empty($list)) {
                    return false;
                }
                /**
                 * @var CouponBrand $couponBrand
                 */
                foreach ($list as $couponBrand) {
                    if ($couponBrand->isEmpty()) {
                        continue;
                    }
                    $couponBrand->old_image = $couponBrand->image_url.'||'.$couponBrand->icon;
                    $couponBrand->save();
                }
            });
        echo '图片备份完成';
    }

    public function down()
    {
        $this->table('coupon_brand')->removeColumn('old_image');
    }
}
